<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名" prop="taxonName">
        <el-input
          v-model="queryParams.taxonName"
          placeholder="请输入试卷名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
       <el-select  v-model="queryParams.courseId" placeholder="请选择课程" style="width: 100%;">
         <el-option
           v-for="dict in courseList"
           :key="dict.value"
           :label="dict.label"
           :value="dict.value"
         >
         </el-option>
       </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['yljf:taxon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['yljf:taxon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['yljf:taxon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['yljf:taxon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taxonList" @selection-change="handleSelectionChange">

      <el-table-column type="expand">
        <template slot-scope="props">
          <!-- style="width: 1200px;" -->
            <el-card class="box-card" >
              <div slot="header" class="clearfix">
                <span>{{ props.row.taxonName }}</span>
                <el-row :gutter="10" class="mb8" style="float: right;">
                  <el-col :span="1.5">
                    <el-button
                      type="primary"
                      plain
                      icon="el-icon-plus"
                      size="mini"
                      @click="handleAdd1"
                      v-hasPermi="['yljf:test_paper:add']"
                    >新增</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="success"
                      plain
                      icon="el-icon-edit"
                      size="mini"
                      :disabled="single1"
                      @click="handleUpdate1"
                      v-hasPermi="['yljf:test_paper:edit']"
                    >修改</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="danger"
                      plain
                      icon="el-icon-delete"
                      size="mini"
                      :disabled="multiple1"
                      @click="handleDelete1"
                      v-hasPermi="['yljf:test_paper:remove']"
                    >删除</el-button>
                  </el-col>
                 <!-- <el-col :span="1.5">
                    <el-button
                      type="warning"
                      plain
                      icon="el-icon-download"
                      size="mini"
                      @click="handleExport1"
                      v-hasPermi="['yljf:test_paper:export']"
                    >导出</el-button>
                  </el-col> -->
                </el-row>
              </div>
              <div  class="text item">
                <el-table  :data="props.row.children" style="width: 100%"
                @selection-change="handleSelectionChange1">
                  <el-table-column type="selection"  align="center" />
                  <el-table-column width="100" label="主键id" align="left" prop="id" />
                  <el-table-column width="300" label="试卷名" align="left" prop="paperTaxon" >
                    <template slot-scope="scope">
                      <div class="cell-content">{{scope.row.paperTaxon.taxonName}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column width="400" label="题目" align="left" prop="courseQuestionId">
                    <template slot-scope="scope">
                      <div class="cell-wrap">
                        <div class="question-content">{{scope.row.questionTitle}}</div>
                        <div class="pick-item" v-for="item in scope.row.questionOptionsList">{{item}}</div>
                      </div>
                    </template>

                  </el-table-column>
                  <el-table-column width="100" label="排序" align="left" prop="sort" />
                  <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate1(scope.row)"
                        v-hasPermi="['yljf:test_paper:edit']"
                      >修改</el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete1(scope.row)"
                        v-hasPermi="['yljf:test_paper:remove']"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>

        </template>
      </el-table-column>

      <el-table-column type="selection" width="55" align="center" />
      <el-table-column width="100" label="主键id" align="left" prop="taxonId" />
      <el-table-column width="250" label="试卷名" align="left" prop="taxonName" >
        <template slot-scope="scope">
          <div class="cell-content">{{scope.row.taxonName}}</div>
        </template>
      </el-table-column>
      <el-table-column width="300" label="课程" align="left" prop="courseName" >
        <template slot-scope="scope">
          <div class="cell-content">{{scope.row.courseName}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['yljf:taxon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['yljf:taxon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程试卷列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="试卷名" prop="taxonName">
          <el-input v-model="form.taxonName" placeholder="试卷名" />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select  v-model="form.courseId" placeholder="请选择课程" style="width: 100%;">
            <el-option
              v-for="dict in courseList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改考试-题目关联表对话框 -->
    <el-dialog :title="title1" :visible.sync="open1" width="600px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="80px">
        <el-form-item label="试卷id" prop="paperTaxonId">
          <!-- <el-input v-model="form1.paperTaxonId" placeholder="请输入试卷id" /> -->

          <el-select  v-model="form1.paperTaxonId" placeholder="请选择试卷" style="width: 100%;">
            <el-option
              v-for="dict in taxonSelect"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="题目id" prop="courseQuestionId">

          <el-table ref="questionTable" class="questionTable" height="270" :data="baseQuestionBankList" @select="baseSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column width="60" label="id" align="center" prop="id" />
            <el-table-column width="280" label="题目" align="center" prop="questionTitle" >
               <template slot-scope="scope">
                 <div class="cell-wrap">
                   <div class="question-content">{{scope.row.questionTitle}}</div>
                   <div class="pick-item" v-for="item in scope.row.questionOptionsList">{{item}}</div>
                 </div>
               </template>
             </el-table-column>
             <el-table-column width="80" label="正确答案" align="center" prop="correctAnswer" />
          </el-table>

          <pagination
            layout="total, prev, pager, next"
            v-show="questionTotal>0"
            :total="questionTotal"
            :page.sync="questionQueryParams.pageNum"
            :limit.sync="questionQueryParams.pageSize"
            @pagination="getListBaseQuestionBank"
          />
          <!-- <el-input v-model="form1.courseQuestionId" placeholder="请输入题目id" /> -->
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number  v-model="form1.sort" controls-position="right" placeholder="请输入排序" :min="1" :max="100"></el-input-number>
          <!-- <el-input v-model="form1.sort" placeholder="请输入排序" /> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listTaxon, getTaxon, delTaxon, addTaxon, updateTaxon } from "@/api/yljf/taxon";
import { listTest_paper, getTest_paper, delTest_paper, addTest_paper, updateTest_paper } from "@/api/yljf/test_paper";
import {
    listCourse
  } from "@/api/yljf/course";

import {
    listBaseQuestionBank
  } from "@/api/yljf/baseQuestionBank";
export default {
  name: "Taxon",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,


      ids1: [],

      single1: true,

      multiple1: true,


      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程试卷列表表格数据
      taxonList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      title1: "",
      // 是否显示弹出层
      open1: false,
      courseList: [

      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taxonName: null,
        courseId: null,
        test: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        courseId: [
          { required: true, message: "课程id不能为空", trigger: "blur" }
        ],
      },

      // 表单参数
      form1: {},
      // 表单校验
      rules1: {
        paperTaxonId: [
          { required: true, message: "试卷id不能为空", trigger: "blur" }
        ],
      },

      taxonSelect:[],

      baseQuestionBankList:[],
      questionTotal:0,
      questionQueryParams:{
        pageNum: 1,
        pageSize: 10,
      },

    };
  },
  created() {
    this.getAllList()
    this.getListBaseQuestionBank()
    this.getListCourse()
    this.getList();
  },
  methods: {
    /** 查询课程试卷列表列表 */
    getAllList(){
      listTaxon({pageSize: 200}).then(response => {
        this.taxonSelect = response.rows.map((item) => {
          return {
            value: item.taxonId,
            label: item.taxonName
          }
        })
      })
    },

    getListBaseQuestionBank() {
      listBaseQuestionBank(this.questionQueryParams).then(response => {

        this.baseQuestionBankList = response.rows.map(item=>{
          item.questionOptionsList = this.getQuestionOptionsList(JSON.parse(item.questionOptions))
          return item
        });

        this.questionTotal = response.total;
        console.log(response)
      })
    },

    // 多选框选中数据
    baseSelectionChange(selection) {
      console.log(selection)
      if(selection.length == 0){
        this.form1.courseQuestionId = null
      } else {
        var select = selection[selection.length - 1]
        if(selection.length > 1){
          this.$refs.questionTable.clearSelection();
          this.$refs.questionTable.toggleRowSelection(select);
        }
        this.form1.courseQuestionId = select.id
      }

    },



    getList() {
      this.loading = true;
      listTaxon(this.queryParams).then(response => {

        listTest_paper({pageSize: 500}).then(res => {
          // this.test_paperList = response.rows;
          console.log(res,res.rows)
          this.taxonList = response.rows.map(item=>{
            item.children = []
            res.rows.forEach(item1=>{
              if(item.taxonId == item1.paperTaxonId){
                if(item1.question){
                  item1.questionTitle = item1.question.questionTitle
                  item1.questionOptionsList = this.getQuestionOptionsList(JSON.parse(item1.question.questionOptions))
                } else {
                  item1.questionTitle = ''
                  item1.questionOptionsList = []
                }

                item.children.push(item1)
              }
            })
            return item
          })
          console.log(this.taxonList)
          this.total = response.total;
          this.loading = false;
          // 创建树形结构
          // response.rows.map(v=>{
          //   v.children=[]
          //   item.rows.map(it=>{
          //     if(v.id==it.courseId){
          //       v.children.push(it)
          //     }
          //   })
          // })

        });


      });
    },

    getQuestionOptionsList(questionOptions){
      var arr = []
      for (var key in questionOptions) {
        arr.push(key+'.'+questionOptions[key])
      }
      return arr
    },

    getListCourse() {
      listCourse({
        pageNum: 1,
        pageSize: 500,
      }).then(response => {
        // console.log(response.rows.le)
        this.courseList = response.rows.map((item) => {
          return {
            value: item.id,
            label: item.name
          }
        })

        // this.courseList = this.courseList.concat(this.courseList,this.courseList)
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taxonId: null,
        taxonName: null,
        createTime: null,
        courseId: null,
        test: null
      };
      this.resetForm("form");
    },

    // 取消按钮
    cancel1() {
      this.open1 = false;
      this.reset1();
    },
    // 表单重置
    reset1() {
      this.form1 = {
        id: null,
        paperTaxonId: null,
        courseQuestionId: null,
        sort: null,
        createTime: null
      };
      this.resetForm("form1");
    },



    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taxonId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    handleSelectionChange1(selection) {
      this.ids1 = selection.map(item => item.id)
      this.single1 = selection.length!==1
      this.multiple1 = !selection.length
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程试卷列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taxonId = row.taxonId || this.ids
      getTaxon(taxonId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程试卷列表";
      });
    },


    /** 新增按钮操作 */
    handleAdd1() {
      this.reset1();
      this.open1 = true;
      this.title1 = "添加考试-题目关联表";
    },
    /** 修改按钮操作 */
    handleUpdate1(row) {
      this.reset1();
      const id = row.id || this.ids1
      getTest_paper(id).then(response => {
        this.form1 = response.data;
        this.open1 = true;
        this.title1 = "修改考试-题目关联表";
      });
    },






    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taxonId != null) {
            updateTaxon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTaxon(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taxonIds = row.taxonId || this.ids;
      this.$modal.confirm('是否确认删除课程试卷列表编号为"' + taxonIds + '"的数据项？').then(function() {
        return delTaxon(taxonIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yljf/taxon/export', {
        ...this.queryParams
      }, `taxon_${new Date().getTime()}.xlsx`)
    },


    /** 提交按钮 */
    submitForm1() {
      console.log(this.form1)
      this.$refs["form1"].validate(valid => {
        if (valid) {
          this.$refs.questionTable.clearSelection();
          if (this.form1.id != null) {
            updateTest_paper(this.form1).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open1 = false;
              this.getList();
            });
          } else {
            addTest_paper(this.form1).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open1 = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete1(row) {
      console.log(this.ids1)
      const ids = row.id || this.ids1;
      this.$modal.confirm('是否确认删除考试-题目关联表编号为"' + ids + '"的数据项？').then(function() {
        return delTest_paper(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('yljf/test_paper/export', {
    //     ...this.queryParams
    //   }, `test_paper_${new Date().getTime()}.xlsx`)
    // }





  }
};
</script>
<style lang="scss" scoped>
  .cell-content{
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2; /* 限制行数为3 */
      overflow: hidden;
  }

  .question-content{
      // display: -webkit-box;
      // -webkit-box-orient: vertical;
      // -webkit-line-clamp: 3; /* 限制行数为3 */
      // overflow: hidden;
      display: flex;
      text-align: left;
  }

  .pick-item{
    display: flex;
  }
</style>
